package com.sxfq.loansupermarket.backsystem.modular.weixin.service.impl;

import com.alibaba.fastjson.JSON;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.MembersUser;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.QueryInfo;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.iconInfoStatus;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.MemberProductService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.CaseInfo;
import com.sxfq.loansupermarket.backsystem.modular.weixin.config.SignUtil;
import com.sxfq.loansupermarket.backsystem.modular.weixin.config.WebChatConfig;
import com.sxfq.loansupermarket.backsystem.modular.weixin.config.WebChatUtil;
import com.sxfq.loansupermarket.backsystem.modular.weixin.entity.*;
import net.sf.json.JSONObject;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sxfq.loansupermarket.backsystem.modular.weixin.service.IWxService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class WxServiceImpl implements IWxService {
    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    private MemberProductService memberProductService;

    //微信模板接口(预约提醒)
    public void sendAppointmentMessage(String openId, String treatmentUnit, String projectData, String doctor, String reservationsNum,
                                       String customerName, String startTimeValue, String reservationsId, String customerPhone) {
        //因为我申请的模板是需要填写当前时间戳的，所以在这里我获取了当前的时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH时mm分");
        String format = simpleDateFormat.format(new Date());
        String access_token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        String templateId = "E2z7GEAsVF1ccnhcVj10qZ6YO1saX0Maet5kL0_xpl0";//填写申请的模板id
        String goUrl = "http://test.yiyatest.cn:8787/integralMallWeixin/medicalRecords";//填写点击推送的消息需跳转到的url
        Data_style first = new Data_style();
        Data_style keyword1 = new Data_style();
        Data_style keyword2 = new Data_style();
        Data_style keyword3 = new Data_style();
        Data_style keyword4 = new Data_style();
        Data_style keyword5 = new Data_style();
        Data_style remark = new Data_style();

        NewOrdersTemplate temp = new NewOrdersTemplate();
        Data data = new Data();
        String fullname = ShiroKit.getUser().getFullname();

        first.setValue(format + "\n" + fullname);
        first.setColor("#173177");

        keyword1.setValue(customerName);
        keyword1.setColor("#173177");

        keyword2.setValue(reservationsNum);
        keyword2.setColor("#173177");
        keyword3.setValue(treatmentUnit + "(" + projectData.replace(",", "") + ")");
        keyword3.setColor("#173177");

        keyword4.setValue(doctor);
        keyword4.setColor("#173177");

        keyword5.setValue(startTimeValue);
        keyword5.setColor("#173177");
        String address = ShiroKit.getUser().getAddress();
        remark.setValue(address + "(" + ShiroKit.getUser().getPhone() + ")" + "\n" +
                "温馨提示：请您于就诊当日按照预约时间段提前到店等候，如需改期请与就诊前一日联系取消。");
        remark.setColor("#173177");

        data.setFirst(first);
        data.setKeyword1(keyword1);
        data.setKeyword2(keyword2);
        data.setKeyword3(keyword3);
        data.setKeyword4(keyword4);
        data.setKeyword5(keyword5);
        data.setRemark(remark);

        temp.setTouser(openId);
        temp.setTemplate_id(templateId);
        temp.setUrl(goUrl);
        temp.setTopcolor("#173177");
        temp.setData(data);

        String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
        com.alibaba.fastjson.JSONObject jsonObject = WebChatUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
    }

    //微信模板接口(术后医嘱)
    public void sendMedicalAdviceMessage(String openId, String doctor, String medicalAdviceTitle, String content) {
        //因为我申请的模板是需要填写当前时间戳的，所以在这里我获取了当前的时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH时mm分");
        String format = simpleDateFormat.format(new Date());
        String access_token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        String templateId = "ja5-Tcs9o1-8CMXo3Y9haQeN1gy6sC2vrQPCDsj7xco";//填写申请的模板id
        String goUrl = "http://test.yiyatest.cn:8787/integralMallWeixin/integralPushMessage/" + medicalAdviceTitle;//填写点击推送的消息需跳转到的url
        Data_style first = new Data_style();
        Data_style keyword1 = new Data_style();
        Data_style keyword2 = new Data_style();
        Data_style remark = new Data_style();
        NewOrdersTemplate temp = new NewOrdersTemplate();
        Data data = new Data();

        first.setValue(format);
        first.setColor("#173177");

        keyword1.setValue(doctor);
        keyword1.setColor("#173177");

        keyword2.setValue(medicalAdviceTitle);
        keyword2.setColor("#173177");

        remark.setValue(content.replace("<br>", ""));
        remark.setColor("#173177");

        data.setFirst(first);
        data.setKeyword1(keyword1);
        data.setKeyword2(keyword2);
        data.setRemark(remark);

        temp.setTouser(openId);
        temp.setTemplate_id(templateId);
        temp.setUrl(goUrl);
        temp.setTopcolor("#173177");
        temp.setData(data);

        String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
        com.alibaba.fastjson.JSONObject jsonObject = WebChatUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
    }

    @ResponseBody
    @RequestMapping(value = "/getWxUserInfoList", method = RequestMethod.GET)
    public Map getWxUserInfoList(String code, String encryptedData, String iv) {
        String accessToken = getAccessToken();
        String URL = ("https://api.weixin.qq.com/cgi-bin/user/get?access_token=accessToken").replace("accessToken", accessToken);
        com.alibaba.fastjson.JSONObject jsonObject = httpRequest(URL, "GET", null);//发送请求
        // 如果请求成功
        if (null != jsonObject) {
            return jsonObject;
        } else {
            return null;
        }
    }

    //微信模板接口(推送调查问卷)
//    public void sendQuestionnaire(String openId) {
//        //因为我申请的模板是需要填写当前时间戳的，所以在这里我获取了当前的时间
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH时mm分");
//        String format = simpleDateFormat.format(new Date());
//        String firstValue="为提高服务质量，希望您为此次的治疗做出评价";
//        String access_token = getAccessToken();
//        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
//        String templateId = "ja5-Tcs9o1-8CMXo3Y9haQeN1gy6sC2vrQPCDsj7xco";//填写申请的模板id
//        String goUrl = "http://test.yiyatest.cn:8787/integralMallWeixin/integralPushMessage/" + openId;//填写点击推送的消息需跳转到的url
//        Data_style first = new Data_style();
//        Data_style keyword1 = new Data_style();
//        Data_style keyword2 = new Data_style();
//        Data_style remark = new Data_style();
//        NewOrdersTemplate temp = new NewOrdersTemplate();
//        Data data = new Data();
//
//        first.setValue(firstValue);
//        first.setColor("#173177");
//
//        keyword1.setValue("");
//        keyword1.setColor("#173177");
//
//        keyword2.setValue("");
//        keyword2.setColor("#173177");
//
//        remark.setValue("");
//        remark.setColor("#173177");
//
//        data.setFirst(first);
//        data.setKeyword1(keyword1);
//        data.setKeyword2(keyword2);
//        data.setRemark(remark);
//
//        temp.setTouser(openId);
//        temp.setTemplate_id(templateId);
//        temp.setUrl(goUrl);
//        temp.setTopcolor("#173177");
//        temp.setData(data);
//
//        String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
//        com.alibaba.fastjson.JSONObject jsonObject = WebChatUtil.httpRequest(url, "POST", jsonString);
//        System.out.println(jsonObject);
//    }

    public void sendQuestionnaire(String openId, String caseid) {
        String selsql = "select * from members_user where open_id='" + openId + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(selsql, MembersUser.class);
        //因为我申请的模板是需要填写当前时间戳的，所以在这里我获取了当前的时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH时mm分");
        String format = simpleDateFormat.format(new Date());
        String firstValue = "为提高服务质量，希望您为此次的治疗做出评价";
        String access_token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        String templateId = "rTkWWQYQv0VosAq_Y5_u8rE4d6lrwrefw1alPu0kVrw";//填写申请的模板id
        String goUrl = "http://test.yiyatest.cn:8787/integralMallWeixin/questionnaire/" + openId + "/" + caseid;//填写点击推送的消息需跳转到的url
        Data_style first = new Data_style();
        Data_style keyword1 = new Data_style();
        Data_style keyword2 = new Data_style();
        Data_style remark = new Data_style();
        NewOrdersTemplate temp = new NewOrdersTemplate();
        Data data = new Data();

        first.setValue(firstValue);
        first.setColor("#173177");

        keyword1.setValue(membersUser.getMembersNum());
        keyword1.setColor("#173177");

        keyword2.setValue(membersUser.getName());
        keyword2.setColor("#173177");

        remark.setValue("");
        remark.setColor("#173177");

        data.setFirst(first);
        data.setKeyword1(keyword1);
        data.setKeyword2(keyword2);
        data.setRemark(remark);

        temp.setTouser(openId);
        temp.setTemplate_id(templateId);
        temp.setUrl(goUrl);
        temp.setTopcolor("#173177");
        temp.setData(data);

        String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
        com.alibaba.fastjson.JSONObject jsonObject = WebChatUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
    }

    //问卷调查推送
    public void questionnaire() {
        String sql = "select a.*,DATE_ADD(update_time, INTERVAL 7 DAY) as timeTwo from case_info a where statusic=2 " +
                " and left(now(),10)= left(DATE_ADD(update_time, INTERVAL 7 DAY),10) ";  //医生点了已完成，七天后发送问卷
        List<iconInfoStatus> ist = sqlMapper.selectList(sql, iconInfoStatus.class);
        for (iconInfoStatus it : ist) {
            String selsql2 = "select open_id from members_user where reservations_id='" + it.getReservationsId() + "' and (open_id!='' or open_id is not null) limit 1";
            MembersUser membersUser = sqlMapper.selectOne(selsql2, MembersUser.class);
            if (membersUser != null) {
                memberProductService.sendQuestionnaire(membersUser.getOpenId(), it.getId());
                String upd2 = "update case_info a set statusic=3 where id='" + it.getId() + "'";  //发送完成修改状态为已发送
                sqlMapper.update(upd2);
            }
        }
        String sql2 = "select a.*,DATE_ADD(update_time, INTERVAL 7 DAY) as timeTwo from case_info a where statusic=1 " +
                " and left(now(),10)= left(DATE_ADD(update_time, INTERVAL 7 DAY),10) "; //未完成的
        List<iconInfoStatus> ist2 = sqlMapper.selectList(sql2, iconInfoStatus.class);
        for (iconInfoStatus it2 : ist2) {
            String sql1 = "select b.department from case_info a left join pay_service_grade_info b on a.pay_service_id=b.id" +
                    " where a.id='" + it2.getId() + "'";
            CaseInfo caseinfo = sqlMapper.selectOne(sql1, CaseInfo.class);
            if (("正畸".equals(caseinfo.getDepartment()) || "种植牙".equals(caseinfo.getDepartment()) || "儿牙-正畸".equals(caseinfo.getDepartment()))) {  //做的正畸或者种植
                String selsql2 = "select open_id from members_user where reservations_id='" + it2.getReservationsId() + "' and (open_id!='' or open_id is not null) limit 1";
                MembersUser membersUser = sqlMapper.selectOne(selsql2, MembersUser.class);
                if (membersUser != null) {
                    memberProductService.sendQuestionnaire(membersUser.getOpenId(), it2.getId());
                    String upd2 = "update case_info a set statusic=3 where id='" + it2.getId() + "'";  //发送完成修改状态为已发送
                    sqlMapper.update(upd2);
                }
            }
        }

    }

    public String getAccessToken() {
        String accessToken = "";
        String getTokenSql = "select access_token as accessToken from wx_parameter_info where app_id='" + WebChatConfig.APPID + "' limit 1";
        WxTokenInfo wxTokenInfo = sqlMapper.selectOne(getTokenSql, WxTokenInfo.class);
        if (wxTokenInfo == null) {
            accessToken = WebChatConfig.getToken(WebChatConfig.APPID, WebChatConfig.SECERT).getAccessToken();
            String updTokenSql = "update wx_parameter_info set access_token='" + accessToken + "' where app_id='" + WebChatConfig.APPID + "';";
            sqlMapper.update(updTokenSql);
        } else {
            if ("".equals(wxTokenInfo.getAccessToken()) || "null".equals(wxTokenInfo.getAccessToken())) {
                accessToken = WebChatConfig.getToken(WebChatConfig.APPID, WebChatConfig.SECERT).getAccessToken();
                String updTokenSql = "update wx_parameter_info set access_token='" + accessToken + "' where app_id='" + WebChatConfig.APPID + "';";
                sqlMapper.update(updTokenSql);
            }
            accessToken = wxTokenInfo.getAccessToken();
        }
        return accessToken;
    }

    public String getOpenid(String code) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (code == null || code.length() == 0) { //登录凭证不能为空
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            System.out.println("map1:" + map);
            ShiroKit.setSessionAttr("wxcode", ShiroKit.getSessionAttr("wxcode"));
            return "code为空";
        } else {
            if (code.equals(ShiroKit.getSessionAttr("wxcode"))) {

            } else {
                ShiroKit.setSessionAttr("wxcode", code);
            }
        }
        String wxspAppid = WebChatConfig.APPID;//wx617f2a7161b844e2 wx77017898334e6e7b
        String wxspSecret = WebChatConfig.SECERT;//2bd57f9adfb912d35cf282e4d79e4205 731fbf6d20a5925c3be5caaa9c4eee07
        String URL = ("https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type" +
                "=authorization_code").replace("APPID", wxspAppid).replace("SECRET", wxspSecret).replace("CODE", ShiroKit.getSessionAttr("wxcode"));
        com.alibaba.fastjson.JSONObject json = httpRequest(URL, "GET", null);//发送请求
        if (json == null){
            return ShiroKit.getSessionAttr("openid");
        } else {
            if (json.size() < 5) {
                return ShiroKit.getSessionAttr("openid");
            } else {
                String openid = (String) json.get("openid");
                if (openid != "" && !openid.equals("") && openid != null) {
                    ShiroKit.setSessionAttr("openid", openid);
                } else {
                    openid = ShiroKit.getSessionAttr("openid");
                }
                System.out.println("openid:" + openid);
                map.put("status", 0);
                map.put("msg", "解密失败");
                String sql = "select * from members_user a where a.open_id='" + openid + "' limit 1;";
                MembersUser user = sqlMapper.selectOne(sql, MembersUser.class);
                if (user != null) {
                    ShiroKit.setSessionAttr("reservationsId", user.getReservationsId());
                } else {
                    ShiroKit.setSessionAttr("reservationsId", null);
                }
                return openid;
            }
        }
    }

    /**
     * 获取随机位数的字符串
     *
     * @author fengshuonan
     * @Date 2017/8/24 14:09
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public void getJsapi_ticket() {
        String access_token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
        String sql = "select media_id from media_type_info limit 1";
        QueryInfo queryInfo = sqlMapper.selectOne(sql, QueryInfo.class);
        Map map = new HashMap();
        map.put("media_id", queryInfo.getMediaId());
        String s = JSON.toJSONString(map);
        String jsonString = JSONObject.fromObject(s).toString().replace("day", "Day");
        com.alibaba.fastjson.JSONObject jsonObject = WebChatUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
        String ticket = jsonObject.getString("ticket");
        ShiroKit.setSessionAttr("JSAPI_TICKET", jsonObject.getString("ticket"));
        ShiroKit.setSessionAttr("JSAPI_TICKET_expires_in", jsonObject.getString("expires_in"));
    }

    public WxParam getEncryptJsapiTicket(String url) {
        String ticket = ShiroKit.getSessionAttr("JSAPI_TICKET");
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//随机生成的时间戳
        String noncestr = getRandomString(16);//生成的16位随机码
        String signature = SignUtil.getSignature(url, timestamp, noncestr);//开始进行sha1签名
        WxParam wxparam = new WxParam();
        wxparam.setNonce(noncestr);
        wxparam.setSignature(signature);
        wxparam.setTimestamp(timestamp);
        return wxparam;
    }

    //get ticket
    public com.alibaba.fastjson.JSONObject qrCodeCreateTmpTicket(String access_token, String sceneStr) {
        String URL = ("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=accessToken").replace("accessToken", access_token);
        GetTicketInfo body = new GetTicketInfo();
        action_info action_info = new action_info();
        scene scene = new scene();
        scene.setScene_str(sceneStr);
        action_info.setScene(scene);
        body.setExpire_seconds(604800);
        body.setAction_name("QR_STR_SCENE");//二维码类型，QR_SCENE为临时的整型参数值，QR_STR_SCENE为临时的字符串参数值，QR_LIMIT_SCENE为永久的整型参数值，QR_LIMIT_STR_SCENE为永久的字符串参数值
        body.setAction_info(action_info);
        String jsonString = JSONObject.fromObject(body).toString();
        com.alibaba.fastjson.JSONObject jsonObject = WebChatUtil.httpRequest(URL, "POST", jsonString);
        System.out.println(jsonObject);
        return jsonObject;
    }

    //get二维码图片路径
    public String qrCodePictureUrl(String ticket) {
        String URL = ("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=Ticket").replace("Ticket", ticket);
//        com.alibaba.fastjson.JSONObject json = httpRequest(URL, "GET", null);//发送请求
        return URL;
    }

    private static com.alibaba.fastjson.JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        com.alibaba.fastjson.JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = com.alibaba.fastjson.JSONObject.parseObject(buffer.toString());
            // jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.out.println("Weixin server connection timed out.");
        } catch (Exception e) {
            System.out.println("https request error:{}" + e.getMessage());
        }
        return jsonObject;
    }

    public static void runtest() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        try {
            Date date = dateFormat.parse("2020-01-09 17:02:00.000");
            new Timer("testTimer1").scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
                }
            }, date, 2000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}